package com.zwq.springbootlearn.controller;

import com.zwq.springbootlearn.model.Result;
import com.zwq.springbootlearn.repository.GirlRepository;
import com.zwq.springbootlearn.model.Girl;
import com.zwq.springbootlearn.service.GirlService;
import com.zwq.springbootlearn.util.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

/**
 * @Author: zwq
 * Create in 2018/6/29 23:19
 */
//类似于@Controller和@Responsebody的组合注解，但是这个RestController是返回json格式
@RestController
public class GirlController {

    private static final Logger logger = LoggerFactory.getLogger(GirlController.class);

    @Autowired
    private GirlRepository girlRepository;

    @Autowired
    private GirlService girlService;

    //查询所有女生列表
    @GetMapping("/girls")
    public List<Girl> girlList(){
        logger.info("girlList");
        //spring data jap不用自己写sql语句
        return girlRepository.findAll();
    };

    //根据id查询一个女生
    @GetMapping("/girls/{id}")
    public Girl getOne(@PathVariable("id") Integer id) throws Exception{

        //根据年龄执行不同的业务
        Girl girl = girlRepository.getOne(id);
        girlService.getAge(id);  //这里会抛出异常
        return girlRepository.findById(id).get();
    }

    /**
     * 添加一个女生
     */
    @GetMapping("/girls/add")
    public Girl girlAdd(@RequestParam("cupSize") String cupSize,
                          @RequestParam("age") Integer age){
        Girl girl = new Girl();
        girl.setCupSize(cupSize);
        girl.setAge(age);

        //数据库插入一条数据
        return girlRepository.save(girl);
    }

    /**
     * 添加一个女生2,使用实体类作为参数
     */
    @GetMapping("/girls/add2")
    public Result<Girl> girlAdd2(@Valid  Girl girl, BindingResult bindingResult){ //表单验证
        //表单验证的结果会自动放在BindingResult中
        if(bindingResult.hasErrors()){
            String msg=bindingResult.getFieldError().getDefaultMessage();
            return ResultUtil.error(1,msg);
        }

        girl.setCupSize(girl.getCupSize());
        girl.setAge(girl.getAge());

        //数据库插入一条数据
        return ResultUtil.success(girlRepository.save(girl));
    }
}
